//
//  BufferHandler.h
//  Medusa
//
//  Created by gww on 13-4-6.
//  Copyright (c) 2013年 Bullets in a Burning Box, Inc. All rights reserved.
//

#ifndef __MEDUSA_BUFFER_HANDLER_H__
#define __MEDUSA_BUFFER_HANDLER_H__

//////////////////////////////////////////////////////////////////////////

#include "Buffer.h"

NS_MEDUSA_BEGIN

class BufferHandler : public Buffer
{
    /*
     public:
     static BufferHandler* New(uint8_t* buf_ptr, size_t bufer_size, size_t data_size=0) {
     BufferHandler* handler_ptr = new BufferHandler(buf_ptr, bufer_size, data_size);
     return handler_ptr;
     }*/
public:
    BufferHandler(void* buf_ptr, size_t bufer_size, size_t data_size=0) {
        this->buffer_ptr    = (uint8_t*)buf_ptr;
		this->buffer_size   = bufer_size;
		this->read_offset   = 0;
		this->write_offset  = data_size;
    }
    
    virtual ~BufferHandler() {
        this->free_buffer();
    }
    
private:
    
    BufferHandler(const BufferHandler& obj) {}
    
    BufferHandler& operator = (const BufferHandler& obj) {
        return *this;
    }
    
    void free_buffer() {
        if(this->buffer_ptr !=NULL) {
            this->buffer_ptr    = NULL;
            this->buffer_size   = 0;
            this->read_offset   = 0;
            this->write_offset  = 0;
        }
    }
    
public:
    
    bool IsFull() const {
        return (this->write_offset == this->buffer_size);
    }
    
    bool IsEmpty() const {
        return (this->write_offset == 0);
    }
    
    void Clear() {
        this->read_offset = this->write_offset = 0;
    }
    
    size_t BufferSize() const {
        return this->buffer_size;
    }
    
    size_t ExpandSize() const {
        return 0;
    }
    
    size_t DataSize() const {
        return this->write_offset - this->read_offset;
    }
    
    size_t FreeSize() const {
        return this->buffer_size - this->write_offset;
    }
    
    size_t LineDataSize() const {
        return this->DataSize();
    }
    
    size_t LineFreeSize() const {
        return this->FreeSize();
    }
    
public:
    
    // Int8
    uint8_t ReadInt8() {
        uint8_t ret = 0;
		if(!this->IsEmpty()) {//this->read_offset < this->write_offset
			ret = this->buffer_ptr[this->read_offset];
			this->read_offset++;
		}
		return ret;
    }
    
    void WriteInt8(uint8_t val) {
        if (!this->IsFull()) {
            this->buffer_ptr[this->write_offset] = val;
            this->write_offset++;
		}
    }
    
    //Ptr
    uint8_t* ReadPtr() const{
        return this->buffer_ptr+this->read_offset;
    }
    
    uint8_t* BufferPtr() const{
        return this->buffer_ptr;
    }
    
private:
    size_t buffer_size;
    size_t read_offset;
    size_t write_offset;
    uint8_t *buffer_ptr;
    
};



NS_MEDUSA_END


#endif //__MEDUSA_BUFFER_HANDLER_H__
